<template>
  <div class="page-container">
    <!-- 搜索栏 -->
    <el-form
      ref="ruleForm"
      :model="searchForm"
      :inline="true"
      class="custom-form">
      <el-row>
        <el-col :span="8">
          <el-form-item label="姓名：" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="性别：" prop="sex">
            <el-select v-model="searchForm.sex" placeholder="请选择性别">
              <el-option v-for="item in optionData.sexOption" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button @click="onReset">重置</el-button>
            <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="mt-10">
      <div class="table-header-btn">
        <el-button type="primary" icon="el-icon-plus" @click="onAdd()">新增</el-button>
        <upload-excel
          style="margin-left: 10px;"
          action="/entwebcc/base/companystations/slave/import.do"
          @uploadSuccess="excelUploadSucces()">
        </upload-excel>
      </div>
      <!-- 表格 -->
      <r-table v-loading="tableLoading" :stripe="true" :data="tableData" :columns="columns" border @selection-change="selectChange" />
      <pagination :total="total" :page.sync="pageNum" :limit.sync="pageSize" @pagination="fetchData" />
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible="dialogStatus"
      :close-on-click-modal="false"
      center
      width="500px"
      append-to-body
      @close="closeDialog">
      <el-form ref="dialogForm" :model="dialogForm" :rules="formRules" label-position="right" label-width="auto">
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="性别：" prop="sex">
          <el-select v-model="dialogForm.sex" placeholder="请选择性别" style="width:100%;">
            <el-option v-for="item in optionData.sexOption" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期：" prop="birthDate">
          <el-date-picker
            v-model="dialogForm.birthDate"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择出生日期"
            style="width:100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="邮箱：" prop="email">
          <el-input v-model="dialogForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="备注：" prop="remark">
          <el-input v-model="dialogForm.remark" :rows="2" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="onConfirm()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UploadExcel from '@/components/Upload/UploadExcel.vue';
import { rtableList } from '@/api/rtable/index';
import { getParams } from '@/utils/tools';
import { checkEmail } from '@/utils/validate';

export default {
  name: 'NTable', // el-table二次封装
  components: {
    UploadExcel,
  },
  data() {
    return {
      // 搜索栏
      searchForm: {
        name: '',
        sex: '',
      },
      // 表格
      tableLoading: false,
      selected: [],
      tableData: [],
      columns: [
        { type: 'selection', width: 55 },
        { type: 'index', label: '序号', width: 50 },
        { prop: 'id', label: 'id', width: 180 },
        {
          prop: 'amount',
          label: '金额',
          width: 150,
          render: (h, { row, column }) => {
            const key = row[column.property];
            const value = this.$options.filters.amountFormat(key);
            return (<span>{ value }</span>);
          }
        },
        {
          prop: 'avatar',
          label: '头像',
          width: 80,
          render: (h, { row, column }) => {
            const key = row[column.property];
            return (<img src={key} style="width:50px;height:50px;"></img>);
          }
        },
        { prop: 'name', label: '姓名', width: 80 },
        {
          prop: 'sex',
          label: '性别',
          width: 100,
          render: (h, { row, column }) => {
            const key = row[column.property];
            const fileObj = {
              0: '女',
              1: '男',
            };
            return (<span>{ fileObj[key] || '/' }</span>);
          }
        },
        { prop: 'birthDate', label: '出生年月日', width: 120 },
        { prop: 'email', label: '邮箱', width: 180 },
        { prop: 'createtime', label: '创建时间', width: 180 },
        { prop: 'remark', label: '备注' },
        {
          prop: 'state',
          label: '状态',
          width: 100,
          fixed: 'right',
          render: (h, { row, column }) => {
            const key = row[column.property];
            const fileObj = {
              0: '禁用',
              1: '启用',
            };
            return (<span>{ fileObj[key] || '/' }</span>);
          }
        },
        {
          label: '操作',
          width: 180,
          fixed: 'right',
          render: (h, { row, column }) => {
            const key = row['state'];
            const fileObj = {
              0: '启用',
              1: '禁用',
            };
            const btnType = {
              0: 'primary',
              1: 'danger',
            };
            return (
              <div>
                <el-button type={btnType[key]} size="mini" onClick={() => this.onAble(row)}>{fileObj[key]}</el-button>
                <el-button type={btnType[0]} size="mini" onClick={() => this.onEdit(row)}>编辑</el-button>
              </div>
            );
          }
        }
      ],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      // 选择数据
      optionData: {
        sexOption: [
          { label: '男', value: 1 },
          { label: '女', value: 0 },
        ]
      },
      // 弹窗
      dialogStatus: false,
      dialogForm: {
        name: '',
        sex: '',
        birthDate: '',
        email: '',
        remark: '',
      },
      // 校验规则
      formRules: {
        name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        sex: [{ required: true, message: '性别不能为空', trigger: 'change' }],
        birthDate: [{ required: true, message: '出生日期不能为空', trigger: 'change' }],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          checkEmail
        ],
      },
      postStatus: 'add'
    };
  },
  computed: {
    dialogTitle() {
      const titleObj = {
        'add': '新增',
        'edit': '编辑',
      };
      return titleObj[this.postStatus];
    }
  },
  mounted () {
    this.fetchData();
  },
  methods: {
    selectChange(val) {
      this.selected = val;
    },
    // 获取列表数据
    async fetchData () {
      const setObj = {
        data: this.searchForm,
        pageSize: this.pageSize,
        pageNum: this.pageNum,
      };
      const params = getParams(setObj);
      this.tableLoading = true;
      const res = await rtableList(params);
      this.tableLoading = false;
      console.log(res, 'fetchData');
      const { rows, total } = res.data;
      this.tableData = rows;
      this.total = total;
    },
    onReset() {
      this.pageNum = 1;
      this.fetchData();
    },
    onSearch() {
      this.pageNum = 1;
      this.fetchData();
    },
    onAdd() {
      this.postStatus = 'add';
      this.dialogStatus = true;
      this.$nextTick(() => {
        this.$refs['dialogForm'].resetFields();
      });
    },
    onEdit (row) {
      this.postStatus = 'edit';
      this.dialogStatus = true;
      const {
        name,
        sex,
        birthDate,
        email,
        remark,
      } = row;
      this.dialogForm = {
        name,
        sex,
        birthDate,
        email,
        remark,
      };
    },
    closeDialog () {
      this.dialogStatus = false;
    },
    onConfirm () {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          this.dialogStatus = false;
          console.log(this.dialogForm, 'dialogForm');
        }
      });
    },
    // 启用/禁用
    onAble({ id, state }) {
      const name = state === 1 ? '禁用' : '启用';
      this.$confirm('', `请确认是否要${name}该学生`, () => {
        console.log(id, state, name);
        this.fetchData();
      });
    },
    // 导入成功回调
    excelUploadSucces(res) {
      this.$message.success(res.message);
      this.onSearch();
    },
    imgUploadSucces (data) {
      console.log(data, 'data');
      this.$set(this.detailForm, 'avatar', data);
    },
  }
};
</script>

<style lang="scss" scoped>
</style>
